import json
from django.core.management.base import BaseCommand
from django.utils import timezone
from system.models import Department  # 请替换 your_app 为你的 app 名称

class Command(BaseCommand):
    help = 'Import department data from dept.json'

    def handle(self, *args, **options):
        Department.objects.all().delete()
        try:
            # 打开并读取 JSON 文件
            with open(r'sql/dept.json', 'r', encoding='utf-8') as file:
                data = json.load(file)

            # 用于存储父部门 ID 映射的字典
            parent_id_mapping = {}

            # 首先处理顶级部门
            for item in data['data']:
                if item['pid'] == 0:
                    parent = None
                else:
                    parent = parent_id_mapping.get(item['pid'])

                # 创建部门对象
                dept = Department(
                    pid=parent,
                    name=item['name'],
                    status=item['status'],
                    remark=item['remark']
                )
                dept.save()

                # 存储新的自增 ID 映射
                parent_id_mapping[dept.id] = 1

                # 处理子部门
                if 'children' in item:
                    self.process_children(item['children'], dept)

            self.stdout.write(self.style.SUCCESS('Data imported successfully.'))
        except Exception as e:
            self.stderr.write(self.style.ERROR(f'Error importing data: {e}'))

    def process_children(self, children, parent):
        for child in children:
            # 创建子部门对象
            dept = Department(
                pid=parent,
                name=child['name'],
                status=child['status'],
                remark=child['remark']
            )
            dept.save()
